package com.cefa.edu.controller;

import com.alibaba.fastjson.JSONObject;
import com.cefa.edu.common.ConstantProperties;
import com.cefa.edu.common.TransformationUtils;
import com.cefa.edu.common.result.FailureResult;
import com.cefa.edu.common.result.Result;
import com.cefa.edu.common.result.ReturnMessage;
import com.cefa.edu.common.result.SuccessResult;
import com.cefa.edu.dao.ClassMapper;
import com.cefa.edu.dao.EducationLevelMapper;
import com.cefa.edu.model.*;
import com.cefa.edu.model.Course;
import com.cefa.edu.model.Role;
import com.cefa.edu.model.User;
import com.cefa.edu.pojo.*;
import com.cefa.edu.pojo.Instructor;
import com.cefa.edu.pojo.Score;
import com.cefa.edu.service.*;
import com.cefa.edu.util.HttpRequestUtil;
import com.cefa.edu.util.MD5Generator;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangzehui
 * @date 18-7-30 上午9:16
 */
@RestController
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    EducationLevelService educationLevelService;
    @Autowired
    UserOrganRoleService userOrganRoleService;
    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    ScoreService scoreService;
    @Autowired
    ConstantProperties constantProperties;


    /**
     * @aa 根据学生毕业年份和学生名称 获取对应的毕业生信息
     * @aa 按照学生名称排序
     */
    @RequestMapping(value = "/education/getGraduates",method=RequestMethod.POST)
    public Result< Map<String,Object>> getGraduates(@Param("schoolId")Integer schoolId,@Param("graduatedYear") String graduatedYear, @Param("name") String name,@Param("pageNo")Integer pageNo,@Param("pageSize")Integer pageSize){
        List<HashMap<String,Object>> graduatesList=null;
        Map<String,Object> result=Maps.newHashMap();
        try{
            //判断 参数graduatedYear 是否时年份格式字符
            Integer gYear=null;
            if(StringUtils.isNotBlank(graduatedYear)){
                gYear=Integer.parseInt(graduatedYear);
            }
            if(schoolId==null ||schoolId==0){
                schoolId=1;
            }
            graduatesList=userService.getGraduates(schoolId,gYear,name,pageNo,pageSize);
            //获取所有毕业生
            Integer totalNumber=userService.getAllCountOfGraduates(schoolId);
            result.put("graduatesList",graduatesList);
            result.put("totalNumber",totalNumber);
        }catch(Exception e){
            logger.error("获取毕业生数据时，出错！ 错误信息："+e.getMessage());
            e.printStackTrace();
            return new FailureResult< Map<String,Object>>(new ReturnMessage("500","failure"));
        }

        //若graduatesList为空 响应状态码也是200
        return new SuccessResult< Map<String,Object>>(new ReturnMessage("200","success"),result);
    }
    /**
     * 添加用户（包括管理者、班主任、老师、学生、监护人）
     * @aa add by chaijian 2018-08-13
     */
    @RequestMapping(path="/education/managerSaveNew", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> managerSave_new(com.cefa.edu.pojo.User user, Integer roleType, Integer levelId, Integer courseId) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {
            //参数校验(非空、参数类型)
            boolean isPass=validateParams(user,roleType,levelId,courseId);
            if(!isPass){
                result.put("falt",false);
            }else {
                //判断将要添加的用户 是否已添加，角色是否已分配
                Map<String,Integer> statusMap=getValidateUserStatus(roleType,user,courseId);
                //解析statusMap
                //map值：1、未添加  2、已添加 未分配角色 3、已添加 已分配角色 4、添加的角色在库中不存在
                if(statusMap!=null && statusMap.size()>0){
                    Integer validateStatus=statusMap.get("validateStatus");

                    if(3==validateStatus||4==validateStatus){
                        //3:已添加 已分配角色 4:添加的角色在库中不存在
                        result.put("falt",false);
                    }else {
                        //把 用户添加、及角色分配放入一个事务中
                        userService.saveUserAndDistributeRole(validateStatus,user,levelId,roleType);
                    }
                }//if(statusMap!=null && statusMap.size()>0)
            }// if(!isPass)
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }

        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    //参数校验(非空、参数类型)
    private boolean validateParams(com.cefa.edu.pojo.User user, Integer roleType, Integer levelId, Integer courseId) {
        /**
         * @aa 1、校验用户部分属性不可为空 有中文名称、登录名、登录密码、身份证号、学校id
         * @aa 2、根据roleType 校验不同的参数
         * @aa     roleType值 1：超级管理者 2：教育阶段管理者 3：年级管理者 4：班主任 5：教师 6：监护人 7：学生
         * @aa    若：roleType为3、4、5、6、7  levelId不可为空
         * @aa    且roleType为5时，courseId不可为空
         * @aa    duties值：若添加用户是 教育阶段管理者、年级管理者 duties值不可为空，其他角色 duties值可以为空
         */

        boolean isPass=true;
        if(roleType==null ||roleType==0){
            return false;
        }else {

            //校验用户部分属性不可为空 判断中文名称、登录名、登录密码、身份证号、学校id 不可为空
            isPass=validatePartParams(user);
            //判断不同roleType 对应的不同levelId是否为空
            if(levelId==null ||levelId==0){
                return false;
            }

            if(isPass){
                switch (roleType){
                    case 2:case 3:
                        //若添加用户是 教育阶段管理者、年级管理者 duties值不可为空
                        if(Strings.isNullOrEmpty(user.getDuties())){
                            return false;
                        }
                        break;
                    case 5:
                        //教师 科目id 不可为空
                        if (courseId==null||courseId==0){
                            return false;
                        }
                        break;
                    case 6:
                        //监护人 监护的学生id、关系、监护人类别是否为空
                        if(user.getStudentId()==null||user.getStudentId()==0){
                            return false;
                        }
                        if(StringUtils.isBlank(user.getRelationship())){
                            return false;
                        }
                        if(user.getType()==null||user.getType()==0){
                            return false;
                        }
                        break;
                }
            }// if(isPass)

        }
        return isPass;
    }

    //校验用户部分属性不可为空 判断中文名称、登录名、登录密码、身份证号、学校id 不可为空
    private boolean validatePartParams(com.cefa.edu.pojo.User user) {
        if(StringUtils.isBlank(user.getName())){
            return false;
        }
        if (StringUtils.isBlank(user.getUserName())){
            return false;
        }
        if(StringUtils.isBlank(user.getPassword())){
            return false;
        }
        if(StringUtils.isBlank(user.getIdCode())){
            return false;
        }
        if(user.getSchoolId()==null || user.getSchoolId()==0){
            return false;
        }
        return true;
    }


    /**
     @aa 添加用户并指定角色
     @aa 操作：
     @aa 1、根据省份证号判断是否已经入库
     @aa 2、是否已经分配了要分配的角色
     */
    public Map<String,Integer> getValidateUserStatus(Integer roleType, com.cefa.edu.pojo.User user, Integer courseId) {
        //map值：1、未添加  2、已添加 未分配角色 3、已添加 已分配角色 4、添加的角色在库中不存在
        Map<String,Integer> resultMap=new HashMap<String,Integer>();
        resultMap.put("validateStatus",2);

        //通过roleType获取对应的角色 若要添加的用户角色在角色表中不存在，直接返回，不继续操作
        // Role role = loginService.getRoleByType(roleType);
        com.cefa.edu.pojo.Role role=roleService.getRoleByRoleType(roleType);
        if(role==null){
            resultMap.put("validateStatus",4);
        }else {
            //判断user类封装的idCode(身份证号是否已使用（已入库）),若未使用，则添加user; 若已使用，判断该身份证对应的用户是否分配了角色
            com.cefa.edu.pojo.User userNew= userService.getUserByIdCode_new(user.getIdCode());

            if(userNew==null){
                resultMap.put("validateStatus",1);
            }else{
                /**
                 * @aa 通过userId、roleType、courseId判断该用户是否已分配了对应的角色
                 * @aa 添加角色为空老师时，courseId不可为空
                 */
                int count=0;
                count=userOrganRoleService.getCountRecordWithUserIdAndRoleTypeAndCourseId(userNew.getId(),roleType,courseId);
                if(count>0){
                    resultMap.put("validateStatus",3);
                }
            }
        }//if(role==null)

        return resultMap;
    }
//    /**
//     * 添加用户（包括管理者、班主任、老师、学生、监护人）
//     * @param user
//     * @param roleType
//     * @return
//     */
//    @RequestMapping(path="/education/managerSave", method = RequestMethod.POST)
//    @CrossOrigin
//    public Result<Map<String,Object>> managerSave(User user,Integer roleType,Integer levelId,Integer courseId) {
//        Map<String, Object> result = Maps.newHashMap();
//       boolean falt= validateUser(roleType,user,levelId,courseId);
//        try {
//            if(falt){
//                userService.insertUserRole(user,roleType,levelId,courseId);
//            }
//            result.put("falt",falt);
//        }catch (Exception e){
//            logger.error(e.getMessage());
//            result.put("falt",false);
//            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
//        }
//        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
//    }

    /**
     * 用户字段验证 和 用户重复验证
     * @param roleType
     * @param user
     * @param levelId
     * @param courseId
     * @return
     */
    public boolean validateUser(Integer roleType,User user,Integer levelId,Integer courseId){
        boolean falt =true;
        Role role = loginService.getRoleByType(roleType);
        if(role==null){
            falt=false;
        }else{
            if("manager".equals(role.getRoleName())){//管理者
                int count=userService.findUserByLevelIdAndIdCode(levelId,user.getIdCode());
                if(count>0){
                    falt=false;
                }
            }else if("instructor".equals(role.getRoleName())){//任课老师
                int count=userService.findUserByLevelIdWithInstructor(levelId,user.getIdCode(),courseId);
                if(count>0){
                    falt=false;
                }
            }else if("director".equals(role.getRoleName())){//班主任
                int count=userService.findUserByLevelIdWithDirector(levelId,user.getIdCode(),user.getDirector());
                if(count>0){
                    falt=false;
                }
            }else if("student".equals(role.getRoleName())){//学生
                com.cefa.edu.pojo.User u=loginService.getUserByLevelIdAndIdCode(levelId,user.getIdCode());
                if(u!=null){
                    falt=false;
                }
            }else if("guardian".equals(role.getRoleName())){//监护人
                if(user.getStudentId()==null||"".equals(user.getStudentId())){
                    falt=false;
                }else if(user.getRelationship()==null||"".equals(user.getRelationship())){
                    falt=false;
                }else if(user.getType()==null||"".equals(user.getType())){
                    falt=false;
                }
            }
        }
        return falt;
    }

    /**
     *添加课程（科目）
     * @param course
     * @return
     */
    @RequestMapping(path="/education/courseSave", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> courseSave(Course course) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            userService.insertCourse(course);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }


    /**
     * 任课老师列表查询
     * @param levelId
     * @return
     */
    @RequestMapping(path="/education/instructorList", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> instructorList(Integer levelId) {
        Map<String, Object> result = Maps.newHashMap();
        List<Instructor> list;
        try {
            list=userService.findDirectorByLevelId(levelId);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        result.put("name",list);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }


    /**
     * 根据年级查询课程（科目）列表
     * @param levelId
     * @return
     */
    @RequestMapping(path="/education/courseList", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> courseList(Integer levelId) {
        Map<String, Object> result = Maps.newHashMap();
        List<Course> list;
        try {
            list=userService.findCourseListByLevelId(levelId);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        result.put("name",list);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * 用户删除
     * @param userId
     * @param levelId
     * @param roleType
     * @return
     */
    @RequestMapping(path="/education/deleteUser", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> deleteUser(Integer userId,Integer levelId,Integer roleType,Integer classId) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {
            //educationLevelService.deleteUserEducationLevel(userId,levelId,roleType,instructorId);
            //1、删除用户在该层级的权限表

            result=  userService.deleteUser(result,userId,levelId,roleType,classId);
            if(result.get("msg")!=null){
                result.put("falt",false);
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * 课程删除
     * @param courseId
     * @return
     */
    @RequestMapping(path="/education/deleteCourse", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> deleteCourse(Integer courseId) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            int count=userService.updateCourseStatus(courseId);
            result.put("falt",count>0?true:false);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }


    @RequestMapping(path="/education/studentList", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> studentList(Integer levelId) {
        Map<String, Object> result = Maps.newHashMap();
        List<User> list=null;
        try {
            list=userService.getStudentByLevelId(6,levelId);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        result.put("name",list);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }


    /**
     * 科目查询
     * @param courseId
     * @return
     */
    @RequestMapping(path="/education/course", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> course(Integer courseId) {
        Map<String, Object> result = Maps.newHashMap();
        Course course=null;
        try {
             course=userService.getCourseById(courseId);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
        }
        result.put("name",course);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * 签名学生成绩数据2
     * @param userId
     * @param roleType
     * @param chainStatus
     * @return
     */
    @RequestMapping(path="/education/studentChainData2", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> studentChainData2(Integer userId ,Integer roleType,Integer chainStatus) {
        Map<String, Object> result = Maps.newHashMap();
        List<ScoreInfo> list=null;
        try {
            list= educationLevelService.studentChainData(userId,roleType,chainStatus);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
        }
        result.put("name",list);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * 自动验证和返回规则用户名
     * @param userName
     * @return
     */
    @RequestMapping(path="/education/checkUserName", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> checkUserName(String userName){
        Map<String, Object> result = Maps.newHashMap();
        String userNamePi="";
        try {
            userNamePi=userService.getUserNamePi(userName);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
        }
        result.put("userName",userNamePi);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * 修改用户
     * @param user
     * @param roleType
     * @return
     */
    @RequestMapping(path="/education/updateUser", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> updateUser(com.cefa.edu.pojo.User user, Integer roleType, Integer levelId){
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {
            //校验
            if(roleType==null ||roleType==0){
                result.put("msg","修改用户时，roleType不可为空！");
            }else if(user.getId()==null ||user.getId()==0){
                result.put("msg","修改用户时，用户id不可为空！");
            }else if(levelId==null ||levelId==0){
                result.put("msg","修改用户时，levelId不可为空！");
            }
            if(roleType==5){
             //班主任改为老师时，科目不可为空
                if(user.getCourseId()==null ||user.getCourseId()==0){
                    result.put("msg","修改班长任改为授课老师时，科目Id不可为空！");
                }
            }
            if(null==result.get("msg")){
                userService.updateUserById(user,roleType,levelId);
            }else {
                result.put("falt",false);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            result.put("msg",e.getMessage());
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    @RequestMapping(path="/education/scoreSign", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>>scoreSign(Integer userId,Integer roleType,Integer scoreId){
        Map<String, Object> result = Maps.newHashMap();
        try {
            //拼接参数数据
            JsonData jsonData = new JsonData();
            com.cefa.edu.pojo.Score score=scoreService.getScoreById(scoreId);
            jsonData.setCourseName(score.getCourseName());
            jsonData.setEduStageName(score.getEduStageName());
            jsonData.setExaminationTime(score.getExaminationTime());
            jsonData.setFraction(score.getFraction());
            jsonData.setGradeName(score.getGradeName());
            jsonData.setRecordingName(score.getRecordingName());
            jsonData.setRecordingPerson(score.getRecordingPerson());
            jsonData.setStudentName(score.getStudentName());

            JSONObject jsonObject2= new JSONObject();
            jsonObject2.put("json",jsonData);
            System.out.println(jsonObject2.toJSONString());
            System.out.println(jsonObject2.toString());
            String stablejsoData=HttpRequestUtil.sendPost(constantProperties.tostablejson,jsonObject2.toJSONString(),"UTF-8");
            String stablejson = com.alibaba.fastjson.JSONObject.parseObject(stablejsoData).get("msg").toString();

            JSONObject jsonObject3= new JSONObject();
            jsonObject3.put("stablejson",stablejson);
            String sha3Data=HttpRequestUtil.sendPost(constantProperties.tosha3,jsonObject3.toJSONString(),"UTF-8");
            String sha3=JSONObject.parseObject(sha3Data).get("msg").toString();
            com.cefa.edu.pojo.User user=userService.getUserById(userId);

            //获取当前签名用户的角色 add by chaijian 2018-09-07
           roleType=this.getCurrentRoleTypeByUserId(score,userId);

            // 监护人或学生签名 使用学生的key_data
            String prikey=user.getKeyData();
            JSONObject jsonObject1= new JSONObject();
            if(roleType.equals(6)){
                Integer studentId= userService.getStudentIdByGuardianId(userId);
                com.cefa.edu.pojo.User student= userService.getUserById(studentId);
                prikey=student.getKeyData();
            }

            jsonObject1.put("prikey",prikey);
            jsonObject1.put("sha3data",sha3);
            String rcSignData=HttpRequestUtil.sendPost(constantProperties.rcsign,jsonObject1.toJSONString(),"UTF-8");
            String rcSign =JSONObject.parseObject(rcSignData).get("msg").toString();

            scoreService.scoreSign(score.getClassId(),userId,roleType,scoreId,rcSign,stablejson,sha3);
            result.put("falt",true);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    //获取当前签名用户的角色
    private Integer getCurrentRoleTypeByUserId(Score score,Integer userId) {
        /**
         * 先判断 该用户有哪些角色  是不是多方
         若是多方
         判断成绩 签名数据是否已赋值 若赋值 继续判断
         */
        List<Map<String,Object>> userOrganRoleMapList=userOrganRoleService.getUserOrganRoleByUserId(userId);
        if(userOrganRoleMapList!=null && userOrganRoleMapList.size()>0){
            Integer roleTypeDB=null;
            Integer managerCheckStatus=score.getManagerCheckStatus();
            Integer instructorCheckStatus=score.getInstructorCheckStatus();
            Integer guardianCheckStatus=score.getGuardianCheckStatus();

            Integer teacherClassId=null;//老师所在班级编号
            Integer teacherCourseId=null;//老师教科目编号
            for(Map<String,Object> uorMap:userOrganRoleMapList){// 2 5
                roleTypeDB=uorMap.get("roleType")!=null?Integer.parseInt(uorMap.get("roleType").toString()):null;
                if(2==roleTypeDB||3==roleTypeDB){
                    //判断有没有签名
                    if(0==managerCheckStatus){
                       return roleTypeDB;
                    }
                }
                if(4==roleTypeDB||5==roleTypeDB){
                    //判断有没有签名
                    if(0==instructorCheckStatus){

                        //角色为多角色时(教育阶段、年级管理者、老师、班主任)，班主任会签其他班的学生成绩（一班班主任会签到二班学生成绩）
                        //修改 若角色是老师，老师只签其所属班或所属科目下的学生成绩
                        teacherClassId=uorMap.get("classId")!=null?Integer.parseInt(uorMap.get("classId").toString()):null;
                        if(!teacherClassId.equals(score.getLevelId())){
                            continue;
                        }
                        if(roleTypeDB.equals(5)){
                            //授课老师
                            teacherCourseId=uorMap.get("courseId")!=null?Integer.parseInt(uorMap.get("courseId").toString()):null;
                            if(teacherCourseId!=null){
                                if(!teacherCourseId.equals(score.getCourseId())){
                                      continue;
                                }
                            }
                        }
                        return roleTypeDB;
                    }
                }
                if(6==roleTypeDB||7==roleTypeDB){
                    //判断有没有签名
                    if(0==guardianCheckStatus){
                        return roleTypeDB;
                    }
                }
            }
            return roleTypeDB;
        }
        return null;
    }


    /**
     * @aa 获取当前系统最早毕业生毕业年份
     * @aa add by chaijian 2018-08-16
     */
    @RequestMapping("/education/getMinGraduatedYear")
    public Result<Map<String,Object>> getMinGraduatedYear(){
        Map<String,Object> result=Maps.newHashMap();
        result.put("falt",true);
        try{
            Integer minYear= userService.getMinGraduatedYear();
            result.put("minYear",minYear);
        }catch (Exception e){
            logger.debug(e.getMessage());
            e.printStackTrace();
            result.put("falt",false);
            result.put("msg",e.getMessage());
        }
        //失败或是执行成功都返回200状态码 结果成功与否有falt标识
        return new SuccessResult<Map<String, Object>>(new ReturnMessage("200","success"),result);
    }

    /**
     * 用户新增----huangzehui
     * @param user
     * @param roleType
     * @param levelId
     * @param courseId
     * @return
     */
    @RequestMapping(path="/education/managerSave", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> managerSave(com.cefa.edu.pojo.User user, Integer roleType, Integer levelId, Integer courseId) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {
            result=validateParams2(result,user,roleType,levelId,courseId);

            if(null==result.get("msg")){
             Map<String,Object> idCodeUserMap=  userService.saveUserAndDistributeRole2(user,levelId,roleType,courseId);
              if(idCodeUserMap.get("msg")!=null){
                  result.put("msg",idCodeUserMap.get("msg"));
                  result.put("name",idCodeUserMap.get("name"));
                  result.put("userName",idCodeUserMap.get("userName"));
              }

            }else{
                result.put("falt",false);
            }
            /*
            boolean isPass=validateParams2(user,roleType,levelId,courseId);
            if(isPass){
                userService.saveUserAndDistributeRole2(user,levelId,roleType,courseId);
            }else{
                result.put("falt",false);
                result.put("msg","参数不对！");
            }*/
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            result.put("msg","系统出错！");
            return new FailureResult<>(new ReturnMessage("500", e.getMessage()), result);
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }
    private  Map<String, Object> validateParams2( Map<String, Object> result,com.cefa.edu.pojo.User user, Integer roleType, Integer levelId, Integer courseId) {
      //  boolean isPass=true;
        if(StringUtils.isBlank(user.getName())){
           // isPass=false;
            result.put("msg","用户中文名称不可为空！");
        }else if (StringUtils.isBlank(user.getUserName())){
           // isPass=false;
            result.put("msg","用户登录名不可为空！");
        }else if(StringUtils.isBlank(user.getPassword())){
           // isPass=false;
            result.put("msg","用户登录密码不可为空！");
        }else if(StringUtils.isBlank(user.getIdCode())){
          //  isPass=false;
            result.put("msg","用户身份证号不可为空！");
        }else if(user.getSchoolId()==null || user.getSchoolId()==0){
          //  isPass=false;
            result.put("msg","用户所属学校不可为空！");
        }else if(roleType==constantProperties.instructor&&(courseId==null||courseId==0)){
          //  isPass=false;
            result.put("msg","用户角色不可为空！");
        }else if(roleType==constantProperties.guardian&&((user.getStudentId()==null||user.getStudentId()==0||StringUtils.isBlank(user.getRelationship())))){
           // isPass=false;
            result.put("msg","监护人监护学生和与学生关系不可为空！");
        }

        if(result.get("msg")==null){
            int count=0;
            com.cefa.edu.pojo.User userNew= userService.getUserByIdCode_new(user.getIdCode());
            if(userNew!=null){
                count=userOrganRoleService.getUserOrganRole(userNew.getUserName(),userNew.getIdCode(),userNew.getId(),roleType,levelId,courseId);
            }
            if(count>0){
                // isPass=false;
                result.put("msg","该身份证号已使用！");
            }
        }
        return result;
    }

    /**
     * @aa  根据用户账号获取密码
     * @aa add by chaijian 2018-08-20
     */
    @RequestMapping("/education/getPasswordByUserName")
    public Result<Map<String,Object>> getPasswordByUserName(String userName){
        Map<String,Object> result=Maps.newHashMap();
        result.put("falt",true);
        if(Strings.isNullOrEmpty(userName)){
            result.put("falt",false);
        }else{
            try {
                String password= userService.getPasswordByUserName(userName);
                result.put("msg",password);
            }catch(Exception e){
                logger.error(e.getMessage());
                e.printStackTrace();
                result.put("falt",false);
            }
        }

        return  new SuccessResult<Map<String, Object>>(new ReturnMessage("200","success"),result);
    }

    /**
     * @aa  根据用户账号和新密码 修改用户原密码
     * @aa add by chaijian 2018-08-20
     */
    @RequestMapping("/education/updatePasswordByUserName")
    public Result<Map<String,Object>> updatePasswordByUserName(String userName,String oldPassword,String newPassword){
        Map<String,Object> result=Maps.newHashMap();
        result.put("falt",true);
        if(Strings.isNullOrEmpty(userName)){
            result.put("msg","用户账号不可为空！");
        }
        if (Strings.isNullOrEmpty(oldPassword)){
            result.put("msg","原密码不可为空！");
        }
        if(Strings.isNullOrEmpty(newPassword)){
            result.put("msg","新密码不可为空！");
        }

        try {
            if(result.get("msg")==null){
                String password= userService.getPasswordByUserName(userName);
                if(Strings.isNullOrEmpty(password)){
                    //库中密码为空时，直接把空密码设置为新密码
                    userService.updatePasswordByUserName(userName,MD5Generator.generatorMD5(newPassword));
                }else {
                    //库中密码不为空时，比较库中密码是否与参数原密码一致
                    oldPassword= MD5Generator.generatorMD5(oldPassword);
                    if(oldPassword.equals(password)){
                        //若一致 设置用户密码为新密码
                        userService.updatePasswordByUserName(userName,MD5Generator.generatorMD5(newPassword));
                    }else {
                        result.put("falt",false);
                        result.put("msg","原密码不对！");
                    }
                }
            }else {
                result.put("falt",false);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            result.put("falt",false);
            result.put("msg","系统出错！");
        }

        return  new SuccessResult<Map<String, Object>>(new ReturnMessage("200","success"),result);
    }



    /**
     * @aa 根据学生id 获取对应的监护人数据接口
     * @aa add by chaijian 2018-08-22
     * @return
     */
    @RequestMapping("/education/getGuardianByStudentId")
    public Result<Map<String,Object>> getCourseById(@Param("studentId")Integer studentId){
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {

            //校验参数是否为空
            if(studentId==null ||studentId==0){
                result.put("falt",false);
                result.put("msg","参数studentId不可为空！");
            }else {
                //获取监护人数据
                Map<String,Object> guardianMap=  userService.getGuardianByStudentId(studentId);
                if(guardianMap!=null){
                    result.put("guardianMap",guardianMap);
                }else{
                    result.put("falt",false);
                }
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            result.put("msg",e.getMessage());
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * @aa //判断指定的省份证号是否已使用
     * @aa add by chaijian 2018-09-04
     * @return
     */
    @RequestMapping("/education/judgeIdCodeExistByIdCode")
    public Result<Map<String,Object>> judgeIdCodeExistByIdCode(String idCode,Integer roleType){
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {

            //校验参数是否为空
            if(Strings.isNullOrEmpty(idCode)){
                result.put("falt",false);
                result.put("msg","参数idCode不可为空！");
                if(roleType==null ||roleType==0){
                    result.put("falt",false);
                    result.put("msg","参数roleType不可为空！");
                }
            }else {
                //判断指定的省份证号是否已使用
             //  boolean isExisted=userService.judgeIdCodeExistByIdCode(idCode);
                com.cefa.edu.pojo.User user=  userService.getUserByIdCode_new(idCode);
                if(user==null){
                    result.put("falt",false);
                    result.put("msg","此身份证号未使用！");
                }else{
                    boolean isExisted=userService.getCountOfUserOrganRoleWityIdCodeAndRoleType(user.getId(),roleType);
                    result.put("msg","此身份证号已使用!");
                    if(isExisted){
                       result.put("detailMsg","roleType指定角色的该用户已经存在！");
                       result.put("editUserId",user.getId());
                    }
                }
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            result.put("msg",e.getMessage());
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }


}

